package com.example;

import com.alibaba.fastjson.JSONObject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.Arrays;
import java.util.List;

public class ExampleMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        EntityManager em = emf.createEntityManager();
        nativeQuery(em,"SHOW TABLES");
        nativeQuery(em,"SELECT * FROM INFORMATION_SCHEMA.CONSTRAINTS WHERE TABLE_NAME='EMPLOYEE'");
        nativeQuery(em,"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='CONSTRAINTS'");
        persistEntity(em);
        loadEntities(em);
        em.close();
        emf.close();
    }
    private static void loadEntities(EntityManager em){
        Query query = em.createQuery("SELECT e from Employee e");
        List<Employee> employees = query.getResultList();
        System.err.println(JSONObject.toJSONString(employees,true));
    }
    private static void persistEntity(EntityManager em){
        Employee e1 = Employee.of("diana","IT");
        Employee e2 = Employee.of("Mike","Admin");
        Employee e3 = Employee.of("Tim","Sales");
        em.getTransaction().begin();
        em.persist(e1);
        em.persist(e2);
        em.merge(e3);
        em.getTransaction().commit();
    }
    private static void nativeQuery(EntityManager em,String s){
        System.err.println("-----------" + s + "------------------");
        Query query = em.createNativeQuery(s);
        List list = query.getResultList();
        for (Object o : list) {
            if (o instanceof Object[]) {
                System.err.println(Arrays.toString((Object[])o));
            }else{
                System.err.println(o);
            }
        }
    }
}
